﻿#include "XVideoThread.h"

#include "XFFMpeg.h"
#include "XAudioPlay.h"

XVideoThread::XVideoThread()
{

}

void XVideoThread::run()
{
    char out[10000] = {0};
    while(!_isExit)
    {
        //判断暂停状态

        //缓冲区
        if(XFFMpeg::init()->getAudioStreamIndex()!=-1){
            int free = XAudioPlay::init()->getFree();
            if(free < 10000)
            {
                msleep(1);
                continue;
            }
        }

        //读取视频帧
        AVPacket pkt = XFFMpeg::init()->read();

        if(pkt.size <= 0)//未打开视频
        {
            //读取AVPacket包，若未打开视频，此时pkt.size必然小于0，线程睡眠一段时间继续。否则我们开始解码视频帧，同时利用线程的睡眠时间控制解码进度进而来控制播放的速度。
            msleep(10);
            continue;
        }

        if(XFFMpeg::init()->getAudioStreamIndex()!=-1){
            //音频优先
            if(pkt.stream_index == XFFMpeg::init()->getAudioStreamIndex())
            {
                XFFMpeg::init()->decode(&pkt);
                av_packet_unref(&pkt);
                int len = XFFMpeg::init()->toPCM(out);
                XAudioPlay::init()->write(out,len);
                continue;
            }
        }else{

            if(pkt.stream_index != XFFMpeg::init()->getVideoStreamIndex())
            {
                av_packet_unref(&pkt);
                continue;
            }
        }

        //解码帧
        XFFMpeg::init()->decode(&pkt);
        {
            av_packet_unref(&pkt);//释放解码空间

//            if(XFFMpeg::init()->getAudioStreamIndex()==-1){//不包含音频
//                if(XFFMpeg::init()->getFPS() > 0){//控制解码的进度
//                    msleep(1000 / XFFMpeg::init()->getFPS());
//                }
//            }
        }
    }
}
